/*
 *所有关于EquipmentType类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*EquipmentTypeService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Linq.Expressions;
using VoL.Domain.Infrastructure;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.Extensions.AutofacManager;
using VOL.Core.Utilities;
using VOL.Domain.Dto;
using VOL.Domain.Infrastructure;
using VOL.Domain.IRepositories;
using VOL.Entity.DomainModels;

namespace VOL.Domain.Services
{
    public partial class EquipmentTypeService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<EquipmentType> _equipmentTypebaseRepository;
        private readonly IBaseRepository<Equipmentledger> _equipmentledgerbaseRepository;
        private readonly IEquipmentTypeRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public EquipmentTypeService(
            IEquipmentTypeRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<EquipmentType> equipmentTypebaseRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            this._equipmentTypebaseRepository = equipmentTypebaseRepository;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        /// <summary>
        /// 获取设备类型树形结构
        /// </summary>
        /// <returns>树形结构数据</returns>
        public async Task<List<EquipmentTypeTree>> GetEquipmentTypeTree()
        {
            try
            {
                // 获取所有设备类型数据
                var allTypes = await _repository.FindAsync(x => true);

                // 构建树形结构
                var treeList = new List<EquipmentTypeTree>();

                // 找出ParentCode为0或null的节点作为根节点
                var rootNodes = allTypes.Where(x => x.ParentCode == 0 || x.ParentCode == null).ToList();

                // 如果没有找到根节点，尝试其他策略
                if (!rootNodes.Any())
                {
                    rootNodes = allTypes.Take(1).ToList();
                }

                // 递归构建树
                foreach (var root in rootNodes)
                {
                    var treeNode = new EquipmentTypeTree
                    {
                        Id = root.Id,
                        EquipmentCode = root.EquipmentCode ?? string.Empty,
                        EquipmentName = root.EquipmentName ?? string.Empty,
                        Status = root.Status ?? 0,
                        Descs = root.Descs ?? string.Empty,
                        ParentCode = root.ParentCode ?? 0,
                        // 使用当前节点的Id作为父编码查找子节点
                        Children = GetChildren(allTypes, root.Id)
                    };

                    treeList.Add(treeNode);
                }

                return treeList;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取树形结构异常: {ex.Message}");
                throw;
            }
        }
        /// <summary>
        /// 更新子节点查找方法，使用int类型的parentId
        /// </summary>
        /// <param name="allTypes"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<EquipmentTypeTree> GetChildren(List<EquipmentType> allTypes, int parentId)
        {
            // 寻找ParentCode等于当前节点Id的记录作为子节点
            var children = allTypes.Where(x => x.ParentCode == parentId).ToList();

            if (!children.Any())
            {
                return new List<EquipmentTypeTree>();
            }

            var treeNodes = new List<EquipmentTypeTree>();

            foreach (var child in children)
            {
                var treeNode = new EquipmentTypeTree
                {
                    Id = child.Id,
                    EquipmentCode = child.EquipmentCode ?? string.Empty,
                    EquipmentName = child.EquipmentName ?? string.Empty,
                    Status = child.Status ?? 0,
                    Descs = child.Descs ?? string.Empty,
                    ParentCode = child.ParentCode ?? 0,
                    // 递归查找子节点，使用当前节点的Id作为父编码
                    Children = GetChildren(allTypes, child.Id)
                };

                treeNodes.Add(treeNode);
            }

            return treeNodes;
        }


        





    }
}
